package io.coderyeah.product.controller;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import io.coderyeah.basic.Result;
import io.coderyeah.product.domain.Product;
import io.coderyeah.product.dto.ProDTO;
import io.coderyeah.product.service.ProductService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @author lqs
 * @date 2022/9/27 9:58
 */
@RestController
@RequestMapping("/product")
@Api("服务管理接口")
public class ProductController {
    @Autowired
    private ProductService productService;

    @ApiOperation("获取服务列表")
    @PostMapping("/list")
    public Result list(@RequestBody ProDTO proDTO) {
        final LambdaQueryWrapper<Product> wrapper = new LambdaQueryWrapper<>();
        if (StrUtil.isNotBlank(proDTO.getKeyword())) {
            wrapper.like(Product::getName, proDTO.getKeyword());
        }
        if (null != proDTO.getState()) {
            wrapper.eq(Product::getState, proDTO.getState());
        }
        List<Product> products = productService.getAllPros(proDTO);
        // 条件查询数量
        final int count = productService.count(wrapper);
        return Result.success(products, (long) count);
    }


    /**
     * 通过主键查询单条数据
     *
     * @param id 主键
     * @return 单条数据
     */
    @GetMapping("{id}")
    public Result selectOne(@PathVariable Long id) {
        return productService.getPetById(id);
    }

    @ApiOperation("删除操作")
    @DeleteMapping("/del/{id}")
    public Result delete(@PathVariable("id") Long id) {
        productService.removeById(id);
        return Result.success(null);
    }

    @ApiOperation("批量删除操作")
    @PatchMapping("/delByBatch")
    public Result delByBatch(@RequestBody List<Long> ids) {
        productService.removeByIds(ids);
        return Result.success(null);
    }

    @ApiOperation("修改状态")
    @PostMapping("/editType")
    public Result editType(@RequestBody ProDTO proDTO) {
        final Product product = new Product();
        product.setId(proDTO.getId());
        product.setState((long) (proDTO.getState() == 1 ? 0 : 1));
        productService.updateById(product);
        return Result.success(null);
    }

    @ApiOperation("添加服务或修改服务")
    @PostMapping("/saveOrUpdate")
    public Result saveOrUpdate(@RequestBody Product product) {
        return productService.saveOrModify(product);
    }

    @PostMapping("/onsale")
    public Result onsale(@RequestBody List<Long> ids) {
        return productService.onsale(ids);
    }

    @PostMapping("/offsale")
    public Result offsale(@RequestBody List<Long> ids) {
        return productService.offsale(ids);
    }
}
